package com.sniper.utils;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FilesUtil {

    /**
     * 生成指定的缩略图地址
     *
     * @param path
     * @param width
     * @param height
     * @return
     */
    public static String getThumbPath(String path, int width, int height) {
        // 组装新图片地址
        String suffix = path.substring(path.lastIndexOf("."));
        String thumbPath = path.substring(0, path.lastIndexOf(".")) + "_" + String.valueOf(width) + "_"
                + String.valueOf(height) + suffix;

        thumbPath = thumbPath.replace("image", "thumb");
        return thumbPath;
    }


    /**
     * 删除单个文件
     *
     * @param sPath 被删除文件的文件名
     * @return 单个文件删除成功返回true，否则返回false
     */
    public boolean deleteFile(String sPath) {
        boolean flag = false;
        File file = new File(sPath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }

    /**
     * 删除目录（文件夹）以及目录下的文件
     *
     * @param sPath 被删除目录的文件路径
     * @return 目录删除成功返回true，否则返回false
     */
    public boolean deleteDirectory(String sPath) {
        // 如果sPath不以文件分隔符结尾，自动添加文件分隔符
        if (!sPath.endsWith(File.separator)) {
            sPath = sPath + File.separator;
        }
        File dirFile = new File(sPath);
        // 如果dir对应的文件不存在，或者不是一个目录，则退出
        if (!dirFile.exists() || !dirFile.isDirectory()) {
            return false;
        }
        boolean flag = true;
        // 删除文件夹下的所有文件(包括子目录)
        File[] files = dirFile.listFiles();
        if (files != null) {
            for (File file : files) {
                // 删除子文件
                if (file.isFile()) {
                    flag = deleteFile(file.getAbsolutePath());
                    if (!flag)
                        break;
                } // 删除子目录
                else {
                    flag = deleteDirectory(file.getAbsolutePath());
                    if (!flag)
                        break;
                }
            }
        }

        if (!flag)
            return false;
        // 删除当前目录
        return dirFile.delete();
    }

    public static boolean move(File srcFile, String destPath) {
        // Destination directory
        File dir = new File(destPath);
        // Move file to new directory
        return srcFile.renameTo(new File(dir, srcFile.getName()));
    }

    public static boolean move(String srcFile, String destPath) {
        // File (or directory) to be moved
        File file = new File(srcFile);

        // Destination directory
        File dir = new File(destPath);

        // Move file to new directory

        return file.renameTo(new File(dir, file.getName()));
    }

    public static void copy(String oldPath, String newPath) {
        try {
            // int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldPath);
            if (oldfile.exists()) {
                InputStream inStream = new FileInputStream(oldPath);
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1024];
                while ((byteread = inStream.read(buffer)) != -1) {
                    // bytesum += byteread;
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
                fs.close();
            }
        } catch (Exception e) {
            System.out.println("error  " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 写入file
     *
     * @param file
     */
    public static void write(File file, String content) throws IOException {
        FileOutputStream out = new FileOutputStream(file);
        IOUtils.write(content.getBytes(), out);
        IOUtils.closeQuietly(out);
    }

    public static void Copy(File oldfile, String newPath) {
        try {
            // int bytesum = 0;
            int byteread = 0;
            // File oldfile = new File(oldPath);
            if (oldfile.exists()) {
                InputStream inStream = new FileInputStream(oldfile);
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1024];
                while ((byteread = inStream.read(buffer)) != -1) {
                    // Fbytesum += byteread;
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
                fs.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String getWebUrl(String webUrl) {

        if (webUrl.endsWith("/")) {
            webUrl = webUrl.substring(0, webUrl.length() - 1);
        }
        return webUrl;
    }


    /**
     * 获取图片储存路径
     *
     * @return
     */
    public static String getSaveDir(String dir) {

        if (!ValidateUtil.isValid(dir)) {
            dir = "image";
        }

        String saveDir = "/public/attachment/three/" + dir + "/";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String ymd = sdf.format(new Date());
        saveDir += ymd + "/";
        return saveDir;
    }

    /**
     * 生成uuid随机数 ,后缀 是否移除横岗
     *
     * @param suffix
     * @param removeBar
     * @return
     */
    public static String getUUIDName(String suffix, boolean removeBar) {

        StringBuilder name = new StringBuilder();
        UUID uuid = UUID.randomUUID();
        name.append(uuid.toString());

        if (!suffix.equals("")) {
            if (!suffix.startsWith(".")) {
                suffix = "." + suffix;
            }
            name.append(suffix);
        }
        if (removeBar) {
            return name.toString().replaceAll("-", "");
        }
        return name.toString();
    }

    public static String UUID() {
        return UUID.randomUUID().toString();
    }

    /**
     * 附件名称获取，获取附件原名称就是去掉_1920x190等字符
     *
     * @param videoPath
     * @return
     */
    public static String removeThumbPath(String videoPath) {

        if (videoPath.contains("_")) {
            videoPath = videoPath.substring(0, videoPath.indexOf("_"))
                    + videoPath.substring(videoPath.lastIndexOf("."));
        }

        return videoPath;
    }

    /**
     * @param filepath
     * @return
     */
    public static String getFileName(String filepath) {

        int a = filepath.lastIndexOf("/");
        int b = filepath.lastIndexOf(".");
        if (a == -1 || b == -1 || b < a) {
            return filepath;
        }
        String newString = "";
        newString = filepath.substring(a + 1, b);

        return newString;
    }

    /**
     * 文火区间后缀带点
     *
     * @param filepath
     * @return
     */
    public static String getFileExt(String filepath) {

        int b = filepath.lastIndexOf(".");
        if (b == -1) {
            return filepath;
        }
        return filepath.substring(b + 1);
    }

    /**
     * 读取文本内容
     *
     * @param path
     * @return
     * @throws IOException
     */
    public static String readFile(String path) throws IOException {
        File file = new File(path);
        if (!file.exists()) {
            return "";
        }

        FileInputStream in = new FileInputStream(file);
        StringBuilder result = new StringBuilder();
        byte buffer[] = new byte[in.available()];
        while ((in.read(buffer)) != -1) {
            String a = new String(buffer);
            result.append(a);
        }

        in.close();
        return result.toString();
    }

    public static boolean writeImageByUrl(URL url, String savePath) {
        BufferedImage image;
        try {
            image = ImageIO.read(url);
            FileOutputStream out = new FileOutputStream(savePath);
            ImageIO.write(image, FilesUtil.getFileExt(savePath), out);
            out.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 读取 InputStream转string
     *
     * @param in
     * @return
     * @throws IOException
     */
    public static String streamToString(InputStream in) throws IOException {

        byte[] buffer = new byte[1024];
        int len;
        StringBuilder result = new StringBuilder();
        while ((len = in.read(buffer)) != -1) {
            String a = new String(buffer, 0, len);
            result.append(a);
        }
        in.close();
        return result.toString();
    }

    /**
     * 解析img文件
     *
     * @param content
     * @return
     */
    public static List<String> encodeImages(String content) {

        List<String> imgs = new ArrayList<>();
        if (StringUtils.isBlank(content)) {
            return imgs;
        }
        String img = "";
        Pattern p_image;
        Matcher m_image;
        String regEx_img = "(<img.*src\\s*=\\s*(.*?)[^>]*?>)";
        p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE);
        m_image = p_image.matcher(content);
        while (m_image.find()) {
            img = m_image.group();
            Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img);
            while (m.find()) {
                String tempSelected = m.group(1);
                imgs.add(tempSelected);

            }
        }
        return imgs;
    }


}
